package base.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * 分析之前为啥没有，复现出现的问题，在于 println打印操作，很耗时间
 *
 * 这个时候对比下，多线程环境下，对比 线程安全 和 非安全的集合
 *
 * concurrentHashMap 正常运行
 *
 * 存在的问题：
 * HashMap put操作会导致 resize
 * 重新计算 key的hash的时候，前后两个线程，一个线程完成了 resize，7指向3
 * 另一个线程操作还没有完成resize，这个时候3指向7.
 * 这个时候 7和3 互相指向
 *
 * Author: shen qi han
 * Date: 2022/4/6 下午2:12
 */
public class ReadAndWriteMain {

    static int n = 10;
    Map<MyEntity, MyEntity> map = new HashMap<>();
//    Map<MyEntity, MyEntity> map = new ConcurrentHashMap<>();
    static int num = 10000;
    static CountDownLatch cdl = new CountDownLatch(n);

    /**
     * override the equal method use to test map put compare
     */
    class MyEntity{
        Integer val = 0;
        public MyEntity(int val){
            this.val = val;
        }
        @Override
        public int hashCode() {
            return this.val;
        }
        @Override
        public boolean equals(Object o) {
            if(o instanceof Integer){
                o = (Integer)0;
            }else{
                return false;
            }
            return o == this.val;
        }
    }

    class MyWriteTask implements Runnable{

        @Override
        public void run() {
            for(int i = 0; i < num; i++){
                map.put(new MyEntity(i), new MyEntity(i));
//                System.out.println(Thread.currentThread().getName() + " write " + i);
            }
            cdl.countDown();
        }
    }

    class MyReadTask implements Runnable{

        @Override
        public void run() {
            for(int i = 0; i < num; i++){
                map.get(i);
//                System.out.println("reade operation" + i);
            }
            cdl.countDown();
        }
    }

    public void testUnSafeMap(){
        ExecutorService pool = Executors.newFixedThreadPool(n);
        for(int i = 0; i < n; i++){
            MyWriteTask writeTask = new MyWriteTask();
            pool.submit(writeTask);
        }

        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        pool.shutdown();
        System.out.println("finish.");
    }

    public static void main(String[] args) {
        ReadAndWriteMain main = new ReadAndWriteMain();
        main.testUnSafeMap();
    }

}
